package at.tasat.solver.queue;

import java.util.Comparator;
import java.util.Iterator;

import at.tasat.solver.VariableOccurencesList;

public class VariableComparator implements Comparator<Integer> {

	private final VariableOccurencesList occurencesList;

	public VariableComparator(VariableOccurencesList occurencesList) {
		this.occurencesList = occurencesList;
	}

	@Override
	public int compare(Integer variableId_1, Integer variableId_2) {
		int occurences1 = occurencesList.getOccurences(variableId_1).getNumberOfOccurences();
		int occurences2 = occurencesList.getOccurences(variableId_2).getNumberOfOccurences();
		int result = -Integer.compare(occurences1, occurences2);
		assert result == 0 ? (occurences1 == occurences2) : (result < 0 ? occurences1 > occurences2 : occurences2 > occurences1);
		return result;
	}

	public boolean isSorted(Iterable<Integer> collection) {
		Iterator<Integer> iterator = collection.iterator();
		if (!iterator.hasNext()) {
			return true;
		}
		int last = iterator.next();
		while (iterator.hasNext()) {
			int cur = iterator.next();
			int lastOccurences = occurencesList.getOccurences(last).getNumberOfOccurences();
			int curOccurences = occurencesList.getOccurences(cur).getNumberOfOccurences();
			if (lastOccurences < curOccurences) {
				return false;
			}
			last = cur;
		}
		return true;
	}

}
